import { getSvgHtml } from '../../svgHtml'
import { clearUrlHttp, drawCardToBase64, DrawCardToBase64Option, handleImageUrlToWebp, replaceHtmlToSafeStr } from '../../utils'
import Card, { CardValue, LOAD_STATUS } from '../card'

export interface ArticleCardInfo {
    act_id: number,
    apply_time: string,
    attributes: number,
    authenMark: string | null,
    author: {
        face: string,
        fans: number,
        level: number,
        mid: number,
        name: string,
        nameplat: {
            condition: string,
            image: string,
            image_small: string,
            level: string,
            name: string,
            nid: number,
        },
        official_verify: {
            desc: string,
            type: number,
        },
        pendant: {
            expire: number,
            image: string,
            name: string,
            pid: number,
        },
        vip: {
            avatar_subscript: number,
            due_date: number,
            label: {
                label_theme: string,
                path: string,
                text: string,
            },
            nickname_color: string,
            status: number,
            theme_type: number,
            type: number,
            vip_pay_type: number,
        }
    }
    banner_url: string,
    categories: {
        id: number,
        name: string,
        parent_id: number,
    }[],
    category: {
        id: number,
        name: string,
        parent_id: number,
    },
    check_state: number,
    check_time: string,
    content_pipc_list: null,
    cover_avid: number,
    ctime: number,
    dispute: null,
    id: number,
    image_urls: string[],
    is_like: boolean,
    list: {
        apply_time: string,
        articles_count: number,
        check_time: string,
        ctime: number,
        id: number,
        image_url: string,
        mid: number,
        name: string,
        publish_time: number,
        read: number,
        reason: string,
        state: number,
        summary: string,
        update_time: number,
        words: number,
    }
    media: {
        area: string,
        cover: string,
        media_id: number,
        score: number,
        season_id: number,
        spoiler: number,
        title: string,
        type_id: number,
        type_name: string,
    },
    mtime: number,
    origin_image_urls: string[],
    origin_template_id: number,
    original: number,
    private_pub: number,
    publish_time: number,
    reprint: number,
    state: number,
    stats: {
        coin: number,
        dislike: number,
        dynamic: number,
        favorite: number,
        like: number,
        reply: number,
        share: number,
        view: number,
    },
    summary: string,
    template_id: number,
    title: string,
    top_video_info: null,
    type: number,
    words: number,
}

export type ArticleCardCreateValue = CardValue<ArticleCardInfo>
export default class ArticleCard extends Card {
    static blotName = 'article-card'
    static className = 'article-card'

    static create(value: ArticleCardCreateValue) {
        // 根据id获取商品信息，将商品新增转为图片，最终插入图片，并将id作为data-id，存入的参数中
        const node: HTMLElement = super.create(value)
        if (value !== null && value?.status === LOAD_STATUS.LOADED) return node
        node.setAttribute('contenteditable', 'false')
        if (!value.src && !value.id) return node
        node.classList.add('card')
        const type = this.verify(value)
        return type === 'render' ? (this.renderHandle(value, node), node) :
            type === 'draw' ? (this.drawHandle(value, node), node) :
                node
    }

    static renderHandle(value: ArticleCardCreateValue, node: HTMLElement) {
        // return node
        value.id && this.renderCard(value).then((dom: HTMLElement) => { node.appendChild(dom) })
    }
    static drawHandle(value: ArticleCardCreateValue, node: HTMLElement) {
        // return node
        const { id } = value
        if (id) {
            const loadingImage = this.createLoadingImage()
            node.appendChild(loadingImage)
            return this.drawCard(id, value).then((res) => {
                value.src = res
                value?.uploadHandle?.(loadingImage, value) || this.uploadHandle?.(loadingImage, value)
                return null
            })
        }
    }
    static renderCard(value: ArticleCardCreateValue) {
        const { id, info } = value
        return id && info ? createLiveCardDom(info).then((res) => {
            return res.dom
        }) : getArticleDetail(id).then((res) => {
            return createLiveCardDom(res[id]).then((res) => {
                return res.dom
            })
        })
    }
    static drawCard(id: string, value: ArticleCardCreateValue) {
        const render = async (v: ArticleCardCreateValue['info']) => {
            const res = await createLiveCardDom(v, { draw: true, wrap: document.querySelector(this.drawWrap) as HTMLElement })
            return res.base64!
        }
        return value.info ? render(value.info) : getArticleDetail(id).then(res => {
            return render(res[id])
        })
    }
}

export const createLiveCardDom = (
    info: ArticleCardCreateValue['info'],
    option?: DrawCardToBase64Option
) => {

    const r = option || {}
    let o = ''
    if (info?.id) {
        const { id, title, image_urls, author } = info || {}

        o = `
            <a class="article-card-holder normal-card" href="//www.bilibili.com/read/cv${id}?from=articleDetail" target="_blank" data-card-type="article" data-card-id="${id}">
                <div class="pointer-events-none article-card-wrap">
                    <div class="card-left">
                        <div class="title-wrap">
                            <div class="multiple-ellipsis ${option?.draw ? 'draw' : ''} title" style="-webkit-box-orient: vertical;">${replaceHtmlToSafeStr(title)}</div>
                        </div>
                        <div class="flex items-center card-status">
                            ${getSvgHtml('up')}
                            <span>${replaceHtmlToSafeStr(author?.name)}</span>
                        </div>
                    </div>
                    <div class="card-right">
                        <div class="cover-wrap">
                            <div class="article-pic" style="background-image: url(${image_urls?.length ? handleImageUrlToWebp(clearUrlHttp(image_urls[0]), 74 * devicePixelRatio, 56 * devicePixelRatio, 1, 1) : ""})"></div>
                        </div>
                    </div>
                </div>
            </a>
        `
    } else {

        o = ` <div class="read-error-card media mobile slim-border">
                  <p class="p-1"></p>
                    <p class="flex items-center justify-center p-2">
                      <i class="card-icon icon-warning mr-1"></i>
                      <span>文章加载失败</span>
                    </p>
                  <p class="p-3"></p>
                </div>`
    }
    r.className = 'card-container article-card'
    // 通过html2Canvas 生成图片后插入
    return drawCardToBase64(o, r)
}

export const getArticleDetail = (itemId: string): Promise<Record<string, ArticleCardCreateValue['info']>> => {
    // 请求接口获取卡片信息
    return Promise.resolve({
        [itemId]: {
            act_id: 0,
            apply_time: "",
            attributes: 24,
            authenMark: null,
            author: {
                face: "https://i1.hdslb.com/bfs/face/c6712277697434a6dc40c0185c0108c39b2fc6fa.jpg",
                fans: 0,
                level: 0,
                mid: 37090048,
                name: "哔哩哔哩创作中心",
                nameplat: {
                    condition: "累计开通大会员总时长>=10年即可获得",
                    image: "https://i0.hdslb.com/bfs/face/5b04cc2fb1c479874cac145eb7ac7098a1e081d9.png",
                    image_small: "https://i1.hdslb.com/bfs/face/b44b390de6b68a9ac7087b3bef07ad90a46101c4.png",
                    level: "稀有勋章",
                    name: "十年大会员",
                    nid: 88
                },
                official_verify: {
                    desc: "哔哩哔哩创作中心官方账号",
                    type: 1,
                },
                pendant: {
                    expire: 0,
                    image: "",
                    name: "",
                    pid: 0
                },
                vip: {
                    avatar_subscript: 1,
                    due_date: 0,
                    label: {
                        label_theme: "ten_annual_vip",
                        path: 'http://i0.hdslb.com/bfs/vip/label_annual.png',
                        text: "十年大会员",
                    },
                    nickname_color: "#FB7299",
                    status: 1,
                    theme_type: 0,
                    type: 2,
                    vip_pay_type: 0,
                }
            },
            banner_url: "https://i0.hdslb.com/bfs/article/cd504bd19ea5a5c67bddb67f221e223778f2a677.jpg",
            categories: [{
                id: 3,
                name: "生活",
                parent_id: 0
            }, {
                id: 15,
                name: "日常",
                parent_id: 3
            }],
            category: {
                id: 15,
                name: "日常",
                parent_id: 3
            },
            check_state: 0,
            check_time: "",
            content_pipc_list: null,
            cover_avid: 0,
            ctime: 1617168647,
            dispute: null,
            id: 10555126,
            image_urls: ['http://192.168.2.219:9000/smart-park/upload/20250521/d698b94bd4db9eeadfdc8300651221ff.png'],
            is_like: false,
            list: {
                apply_time: "",
                articles_count: 0,
                check_time: "",
                ctime: 1540541319,
                id: 33550,
                image_url: "http://i0.hdslb.com/bfs/article/acd0988083e12d9149742dd45a82fe84023ba8e9.png",
                mid: 37090048,
                name: "功能宣发",
                publish_time: 1739865422,
                read: 0,
                reason: "",
                state: 1,
                summary: "产品上线、功能宣发",
                update_time: 1739865387,
                words: 40705,
            },
            media: {
                area: "",
                cover: "",
                media_id: 0,
                score: 0,
                season_id: 0,
                spoiler: 0,
                title: "",
                type_id: 0,
                type_name: "",
            },
            mtime: 1634094301,
            origin_image_urls: ['https://i0.hdslb.com/bfs/article/801bb0ffc9be3a064b6489f2f12bcdcd22c1cbc2.png'],
            origin_template_id: 4,
            original: 1,
            private_pub: 0,
            publish_time: 1617168647,
            reprint: 0,
            state: 0,
            stats: {
                coin: 47,
                dislike: 0,
                dynamic: 0,
                favorite: 542,
                like: 2969,
                reply: 235,
                share: 199,
                view: 997549,
            },
            summary: "亲爱的UP主们创作君又为大家带来新功能【UP主稿件预约】啦~什么是UP主稿件预约？UP主稿件预约是一个预告未来稿件更新的功能稿件更新时会通知已预约的用户前来观看！UP主稿件预约怎么用？UP主电磁力到达Lv4后，就可以使用稿件预约（App端需更新至6.21.0及以上版本）UP主发布稿件预约后，在UP主动态、空间等位置会展示预约信息，用户可点击预约。UP主发布稿件时，需关联预约信息（目前仅支持App端），才能对已预约的观众进行稿件更新提醒。如果UP主撤销预约，已预约的观众将收到预约撤销提醒。UP主如",
            template_id: 4,
            title: "【功能介绍】UP主稿件预约上线啦！",
            top_video_info: null,
            type: 0,
            words: 545,
        },
    })
}
